package com.joshua.spring.controller;

import com.joshua.spring.dto.QueryRuleInfoDTO;
import com.joshua.spring.dto.RuleOptDTO;
import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.entity.vo.GlobalResponse;
import com.joshua.spring.exception.MicroServiceException;
import com.joshua.spring.form.AddDataForm;
import com.joshua.spring.form.QueryRuleInfoForm;
import com.joshua.spring.form.UpdateDataForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.joshua.spring.constant.ConsumerApiConstants.*;
import static com.joshua.spring.constant.ConsumerApiConstants.RestfulRule.*;

/**
 * description
 * package com.joshua.spring.controller
 * classname  RestfulRoleController
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/4/3 10:31
 */
@Slf4j
@RestController
@RequestMapping(RULES)
public class RestfulRuleController {

    private static final String PATH_ID = RestfulRule.PATH_ID;

    @GetMapping(PATH_ID)
    public GlobalResponse ruleInfo(@PathVariable String id) {
        return GlobalResponse.buildSuccess(id);
    }

    @GetMapping(ID_ARRAY)
    public GlobalResponse queryRuleInfosByIds(@RequestParam String[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            throw ResponseEnum.ILLEGAL_REQUEST_PARAM.bdException("id为空");
        }
        return GlobalResponse.buildSuccess(ids);
    }

    @GetMapping(QUERY_MAP)
    public GlobalResponse queryRuleInfosByMap(@RequestParam Map jsonMap) {
        return GlobalResponse.buildSuccess(jsonMap);
    }

    @GetMapping(QUERY_OBJ)
    public GlobalResponse queryRuleInfosByCondition(@ModelAttribute QueryRuleInfoForm form) {
        QueryRuleInfoDTO dto = new QueryRuleInfoDTO();
        BeanUtils.copyProperties(form, dto);
        log.info("Receive method params ===> [QueryRuleInfoDTO---->({})]", dto);
        return GlobalResponse.buildSuccess(dto);
    }

    @PostMapping
    public GlobalResponse addData(@RequestBody AddDataForm form) {
        log.info("add data [{}]", form);
        RuleOptDTO dto = new RuleOptDTO();
        BeanUtils.copyProperties(form, dto);
        dto.setId(System.currentTimeMillis());
        return GlobalResponse.buildSuccess(form);
    }

    @PutMapping(PATH_ID)
    public GlobalResponse updateData(@PathVariable Long id, @RequestBody UpdateDataForm form) {
        log.info("id [{}],form [{}]", id, form);
        RuleOptDTO dto = new RuleOptDTO();
        BeanUtils.copyProperties(form, dto);
        dto.setId(id);
        return GlobalResponse.buildSuccess(dto);
    }

    @DeleteMapping(PATH_ID)
    public GlobalResponse delData(@PathVariable Long id) {
        return GlobalResponse.buildSuccess(id);
    }
}
